<template>
  <div style="border: 1px solid #ccc;width:100%">
    <Toolbar style="border-bottom: 1px solid #ccc;width:100%" :editor="editorRef" :defaultConfig="toolbarConfig"
      :mode="mode" />
    <Editor style="height: 500px; overflow-y: hidden;width:100%" v-model="valueHtml" :defaultConfig="editorConfig"
      :mode="mode" @onCreated="handleCreated" @onChange="onChange" />
  </div>
</template>
<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { message } from 'ant-design-vue';
import { onBeforeUnmount, ref, shallowRef, onMounted, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getToken } from '@/utils/auth';
const baseApiUrl = process.env.VUE_APP_BASE_API;
const props = defineProps({
  content: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  }
});
const emits = defineEmits(["update:content"]);
const mode = ref('default')
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p></p>')

const toolbarConfig = { excludeKeys: ['fullScreen', 'uploadVideo', 'insertVideo', 'emotion', 'todo', 'codeBlock'] };
const editorConfig = { MENU_CONF: {}, placeholder: '请输入内容...', readOnly: props.disabled }
// 上传图片配置
editorConfig.MENU_CONF['uploadImage'] = {
  server: baseApiUrl + 'wangEditor/upload',
  fieldName: 'file',
  headers: {
    Authorization: getToken()
  },
  onError(file: File, err: any, res: any) { 
    message.error(err.message ? err.message : res.message ? res.message : '上传图片错误');
  }
}

onMounted(() => {

})


// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
// 内容发生改变
const onChange = (e) => {
  emits("update:content", e.getHtml())
}
//
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

watch(() => props.content, (newVal) => {
  valueHtml.value = newVal;
}, { immediate: true })

</script>
